package com.robusta.cityuate.activities;

import org.json.JSONException;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Window;
import com.robusta.cityuate.R;
import com.robusta.cityuate.dialogs.ForgetPasswordFragment;
import com.robusta.cityuate.services.CityuateBroadCastReceiver;
import com.robusta.cityuate.services.HTTPService;
import com.robusta.cityuate.services.LoginService;
import com.robusta.cityuate.utils.ConnectionUtils;

public class LoginActivity extends SherlockFragmentActivity implements
		TextWatcher {

	private final String LOGIN_EMAIL = "email";
	private final String LOGIN_PWD = "password";

	private String TAG = LoginActivity.class.getName();
	private Button loginButton;
	private Context mContext = this;
	private EditText emailField;
	private EditText pwdField;
	private CityuateBroadCastReceiver receiver = new CityuateBroadCastReceiver() {

		@Override
		public void onSuccess() {
			loginSuccess();

		}

		@Override
		public void onFailure() {
			loginFail();

		}

		@Override
		public void onCancel() {
			Log.e(TAG, "onCancel");
			setSupportProgressBarIndeterminateVisibility(false);
			enableView();
			ConnectionUtils.clearConnection(mContext, TAG);

		}
	};
	private Button signupButton;
	private Button forgetButton;
	private ForgetPasswordFragment forgetPasswordDialog;
	private ProgressBar progressBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setSupportProgressBarIndeterminateVisibility(false);
		super.onCreate(savedInstanceState);
		// Set the view
		setContentView(R.layout.login_view);
		setSupportProgressBarIndeterminateVisibility(false);

		// Login fields
		emailField = (EditText) findViewById(R.id.usrname);
		pwdField = (EditText) findViewById(R.id.pwd);
		// enable when not empty
		emailField.addTextChangedListener(this);
		pwdField.addTextChangedListener(this);

		progressBar =(ProgressBar) findViewById(R.id.loading);
		
		// Login button action
		loginButton = (Button) findViewById(R.id.btn_login);
		loginButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				try {
					loginConnection();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

		});

		// forgetButton button action
		forgetButton = (Button) findViewById(R.id.btn_forget_pass);
		forgetButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				showForgetPasswordDialog();
			}

		});

		// set signup to switch to registeration activity
		signupButton = (Button) findViewById(R.id.btn_signup);
		signupButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent signupIntent = new Intent(mContext,
						RegistrationActivity.class);
				startActivity(signupIntent);
			}
		});

	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG, "onResume");
		// initiate the receiver
		registerReceiver(receiver, new IntentFilter(TAG));

		// No current connection
		if (ConnectionUtils.isConnecting(mContext, TAG))
		// it was connected
			
		{	
			disableView();
			progressBar.setVisibility(View.VISIBLE);
			setSupportProgressBarIndeterminateVisibility(true);
		} else if (ConnectionUtils.wasConnected(mContext, TAG))
			// connection was successful
			if (ConnectionUtils.isResultSuccessful(mContext, TAG))
				loginSuccess();
			else
				// it failed
				loginFail();

	}

	/**
	 * This method firing the HTTPService intent to call the server with login
	 * data
	 * 
	 * @throws JSONException
	 */

	private void loginConnection() throws JSONException {

		// Check if no connection pop up a dialog
		if (!ConnectionUtils.isNetworkAvailable(mContext)) {
			// No connection
			ConnectionUtils.showNoConnectionDialog(mContext);
			return;
		} else { // Connection is available
			disableView();
			progressBar.setVisibility(View.VISIBLE);
			setSupportProgressBarIndeterminateVisibility(true);
			// start back-ground service to handle registration process
			Intent backgroud_regService = new Intent(this, LoginService.class);
			backgroud_regService.setAction(TAG);

			backgroud_regService.putExtra(LOGIN_EMAIL, emailField.getText()
					.toString());
			backgroud_regService.putExtra(LOGIN_PWD, pwdField.getText()
					.toString());

			startService(backgroud_regService);
			Log.e(TAG, "Fired login service");

		}

	}

	@Override
	protected void onPause() {
		Log.e("onPause", "OnPause");
		unregisterReceiver(receiver);
		if (!ConnectionUtils.isConnecting(mContext, TAG)) {
			ConnectionUtils.clearConnection(mContext, TAG);
		}
		super.onPause();
	}

	/**
	 * when success in login
	 */
	private void loginSuccess() {
		enableView();
		progressBar.setVisibility(View.GONE);
		setSupportProgressBarIndeterminateVisibility(false);
		Log.d(TAG, "loginSuccess method");
		// Intent intent = new Intent(mContext, CityuateMainActivity.class);
		Intent intent = new Intent(mContext, LandingActivity.class);
		startActivity(intent);
		Toast.makeText(mContext, getString(R.string.welcome), Toast.LENGTH_LONG)
				.show();
		finish();

	}

	/**
	 * when login fails
	 */
	private void loginFail() {
		enableView();
		progressBar.setVisibility(View.GONE);
		setSupportProgressBarIndeterminateVisibility(false);
		Log.d(TAG, "FailLogin method");

		// show failure message
		Toast.makeText(mContext, ConnectionUtils.getExtra(mContext, TAG),
				Toast.LENGTH_LONG).show();
		ConnectionUtils.clearConnection(mContext, TAG);
	}

	@Override
	public void afterTextChanged(Editable s) {
		// only enable when there is text in both mail and password
		if ((emailField.getText().length() != 0)
				&& (pwdField.getText().length() != 0))
			loginButton.setEnabled(true);
		else
			loginButton.setEnabled(false);

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// Not needed

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// Not needed

	}

	private void showForgetPasswordDialog() {
		FragmentManager fm = getSupportFragmentManager();
		forgetPasswordDialog = new ForgetPasswordFragment();
		forgetPasswordDialog.show(fm, getString(R.string.forget_password));

	}

	@Override
	public void onBackPressed() {
		if (ConnectionUtils.isConnecting(mContext, TAG)) {
			enableView();
			progressBar.setVisibility(View.GONE);
			setSupportProgressBarIndeterminateVisibility(false);
			Intent loginCancel = new Intent(TAG + HTTPService.CANCEL);
			sendBroadcast(loginCancel);
			ConnectionUtils.clearConnection(mContext, TAG);
		} else
			super.onBackPressed();
	}
	
	private void disableView(){
		loginButton.setEnabled(false);
		emailField.setEnabled(false);
		pwdField.setEnabled(false);
		forgetButton.setEnabled(false);
		signupButton.setEnabled(false);
	}
	
	private void enableView(){
		loginButton.setEnabled(true);
		emailField.setEnabled(true);
		pwdField.setEnabled(true);
		forgetButton.setEnabled(true);
		signupButton.setEnabled(true);
	}

}
